package system;

import pannel.user.PersonalPage;
import pannel.user.User;
import pannel.user.UserManagementPage;
import pannel.product.ProductManagementPage;
import pannel.product.ProductListPage;
import pannel.order.OrderManagementPage;
import pannel.order.UserOrderPage;
import pannel.cart.CartPage;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;

public class SystemGUI extends JFrame {
    private JPanel menuPanel;
    private JPanel contentPanel;
    private CardLayout cardLayout;
    private User currentUser;

    private static class MenuConfig {
        String menuName;
        Class<? extends BasePage> pageClass;

        public MenuConfig(String menuName, Class<? extends BasePage> pageClass) {
            this.menuName = menuName;
            this.pageClass = pageClass;
        }
    }

    private static final Map<String, List<MenuConfig>> ROLE_MENU_MAPPING = new HashMap<>();

    static {
        // ADMIN角色配置
        ROLE_MENU_MAPPING.put("ADMIN", Arrays.asList(
                new MenuConfig("个人信息", PersonalPage.class),
                new MenuConfig("用户管理", UserManagementPage.class),
                new MenuConfig("商品管理", ProductManagementPage.class),
                new MenuConfig("订单管理", OrderManagementPage.class)
        ));
        ROLE_MENU_MAPPING.put("USER", Arrays.asList(
                new MenuConfig("个人信息", PersonalPage.class),
                new MenuConfig("商品列表", ProductListPage.class),
                new MenuConfig("购物车", CartPage.class),
                new MenuConfig("我的订单", UserOrderPage.class)
        ));

    }

    private static final Color MENU_BACKGROUND = new Color(48, 65, 86);
    private static final Color MENU_ITEM_BACKGROUND = new Color(48, 65, 86);
    private static final Color MENU_ITEM_HOVER = new Color(38, 52, 69);
    private static final Color MENU_ITEM_SELECTED = new Color(38, 52, 69);
    private static final Color MENU_TEXT = Color.WHITE;

    public SystemGUI(User user) {
        this.currentUser = user;
        initFrame();
        initComponents();
        layoutComponents();
        setDefaultPage();
    }

    // 提供获取当前用户的方法
    public User getCurrentUser() {
        return currentUser;
    }

    private void initFrame() {
        setTitle("喵喵电商系统 - " + currentUser.getUsername() + " (" + currentUser.getRole() + ")");
        setSize(1200, 800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
    }

    private void initComponents() {
        // 创建主面板作为菜单面板的容器
        JPanel mainMenuPanel = new JPanel(new BorderLayout());
        mainMenuPanel.setPreferredSize(new Dimension(280, getHeight()));
        mainMenuPanel.setBackground(MENU_BACKGROUND);

        // 创���单面板
        menuPanel = new JPanel();
        menuPanel.setBackground(MENU_BACKGROUND);
        menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS));
        menuPanel.add(Box.createVerticalStrut(20));

        // 创建内容面板
        contentPanel = new JPanel();
        cardLayout = new CardLayout();
        contentPanel.setLayout(cardLayout);
        contentPanel.setBackground(Color.WHITE);

        // 添加面板
        mainMenuPanel.add(menuPanel, BorderLayout.NORTH);
        mainMenuPanel.add(createLogoutButton(), BorderLayout.SOUTH);

        add(mainMenuPanel, BorderLayout.WEST);
        add(contentPanel, BorderLayout.CENTER);
    }

    private void layoutComponents() {
        List<MenuConfig> menuConfigs = ROLE_MENU_MAPPING.getOrDefault(currentUser.getRole(), new ArrayList<>());

        for (MenuConfig menuConfig : menuConfigs) {
            JPanel buttonPanel = createMenuButton(menuConfig.menuName);
            menuPanel.add(buttonPanel);
            menuPanel.add(Box.createVerticalStrut(5));

            BasePage pagePanel = createPagePanel(menuConfig.pageClass);
            if (pagePanel != null) {
                contentPanel.add(pagePanel, menuConfig.menuName);
            }
        }
    }

    private JPanel createMenuButton(String menuText) {
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new BorderLayout());
        buttonPanel.setBackground(MENU_ITEM_BACKGROUND);
        buttonPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 60));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));

        JPanel contentPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 40, 0));
        contentPanel.setBackground(MENU_ITEM_BACKGROUND);

        JButton button = new JButton(menuText);
        button.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        button.setBorderPainted(false);
        button.setFocusPainted(false);
        button.setContentAreaFilled(false);
        button.setForeground(MENU_TEXT);

        contentPanel.add(button);
        buttonPanel.add(contentPanel, BorderLayout.CENTER);

        addHoverEffect(buttonPanel, contentPanel, button);
        button.addActionListener(e -> handleMenuClick(menuText, buttonPanel));

        return buttonPanel;
    }

    private BasePage createPagePanel(Class<? extends BasePage> pageClass) {
        try {
            return pageClass.getDeclaredConstructor(User.class).newInstance(currentUser);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private void handleMenuClick(String menuText, JPanel selectedPanel) {
        // 根据菜��名找到对应的页面类
        Class<? extends BasePage> pageClass = null;
        List<MenuConfig> menuConfigs = ROLE_MENU_MAPPING.get(currentUser.getRole());
        for (MenuConfig config : menuConfigs) {
            if (config.menuName.equals(menuText)) {
                pageClass = config.pageClass;
                break;
            }
        }

        // 创建新的页面实例
        if (pageClass != null) {
            try {
                // 找到并移除旧页面
                Component[] components = contentPanel.getComponents();
                for (Component comp : components) {
                    if (comp instanceof BasePage) {
                        if (pageClass.isInstance(comp)) {
                            contentPanel.remove(comp);
                            break;
                        }
                    }
                }

                // 创建并添加新页面
                BasePage newPage = pageClass.getDeclaredConstructor(User.class).newInstance(currentUser);
                contentPanel.add(newPage, menuText);

                // 显示新页面
                cardLayout.show(contentPanel, menuText);
                // 更新菜单选中状态
                updateMenuSelection(selectedPanel);
                // 重新验证并重绘
                contentPanel.revalidate();
                contentPanel.repaint();
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "创建页面失败：" + e.getMessage());
            }
        }
    }

    private void updateMenuSelection(JPanel selectedPanel) {
        for (Component comp : menuPanel.getComponents()) {
            if (comp instanceof JPanel) {
                JPanel panel = (JPanel) comp;
                boolean isSelected = panel == selectedPanel;
                updatePanelColors(panel, isSelected);
            }
        }
    }

    private void updatePanelColors(JPanel panel, boolean isSelected) {
        Color bgColor = isSelected ? MENU_ITEM_SELECTED : MENU_ITEM_BACKGROUND;
        panel.setBackground(bgColor);
        for (Component innerComp : panel.getComponents()) {
            if (innerComp instanceof JPanel) {
                innerComp.setBackground(bgColor);
            }
        }
    }

    private JPanel createLogoutButton() {
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new BorderLayout());
        buttonPanel.setBackground(MENU_ITEM_BACKGROUND);
        buttonPanel.setPreferredSize(new Dimension(Integer.MAX_VALUE, 60));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));

        JPanel contentPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 40, 0));
        contentPanel.setBackground(MENU_ITEM_BACKGROUND);

        JButton button = new JButton("退出系统");
        button.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        button.setBorderPainted(false);
        button.setFocusPainted(false);
        button.setContentAreaFilled(false);
        button.setForeground(MENU_TEXT);

        contentPanel.add(button);
        buttonPanel.add(contentPanel, BorderLayout.CENTER);

        addHoverEffect(buttonPanel, contentPanel, button);
        button.addActionListener(e -> handleLogout());

        return buttonPanel;
    }

    private void addHoverEffect(JPanel buttonPanel, JPanel contentPanel, JButton button) {
        MouseAdapter hoverAdapter = new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                if (buttonPanel.getBackground() != MENU_ITEM_SELECTED) {
                    buttonPanel.setBackground(MENU_ITEM_HOVER);
                    contentPanel.setBackground(MENU_ITEM_HOVER);
                    button.setFont(new Font("微软雅黑", Font.BOLD, 18));
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                if (buttonPanel.getBackground() != MENU_ITEM_SELECTED) {
                    buttonPanel.setBackground(MENU_ITEM_BACKGROUND);
                    contentPanel.setBackground(MENU_ITEM_BACKGROUND);
                    button.setFont(new Font("微软雅黑", Font.PLAIN, 18));
                }
            }
        };

        buttonPanel.addMouseListener(hoverAdapter);
        contentPanel.addMouseListener(hoverAdapter);
        button.addMouseListener(hoverAdapter);

        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        buttonPanel.setCursor(new Cursor(Cursor.HAND_CURSOR));
        contentPanel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    }

    private void handleLogout() {
        int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要退出系统吗？",
                "退出确认",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE
        );

        if (confirm == JOptionPane.YES_OPTION) {
            currentUser = null; // 清除用户信息
            dispose();
            SwingUtilities.invokeLater(() -> {
                LoginRegisterPage loginPage = new LoginRegisterPage();
                loginPage.setLocationRelativeTo(null);
                loginPage.setVisible(true);
            });
        }
    }

    private void setDefaultPage() {
        List<MenuConfig> menuConfigs = ROLE_MENU_MAPPING.get(currentUser.getRole());
        if (menuConfigs != null && !menuConfigs.isEmpty()) {
            String firstMenu = menuConfigs.get(0).menuName;
            cardLayout.show(contentPanel, firstMenu);

            // 设置第一个菜单项为选中状态
            Component[] components = menuPanel.getComponents();
            for (Component comp : components) {
                if (comp instanceof JPanel) {
                    JPanel panel = (JPanel) comp;
                    Component[] innerComps = panel.getComponents();
                    for (Component innerComp : innerComps) {
                        if (innerComp instanceof JPanel) {
                            JPanel contentPanel = (JPanel) innerComp;
                            Component[] btnComps = contentPanel.getComponents();
                            for (Component btnComp : btnComps) {
                                if (btnComp instanceof JButton) {
                                    JButton btn = (JButton) btnComp;
                                    if (btn.getText().equals(firstMenu)) {
                                        updatePanelColors(panel, true);
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}